package com.train.mgr.modules.biz.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.train.common.enums.CheckStatusEnum;
import com.train.common.enums.UserTypeEnum;
import com.train.common.exception.BizException;
import com.train.common.exception.BusinessException;
import com.train.common.model.PageResult;
import com.train.common.model.SysUser;
import com.train.common.utils.AuthUtils;
import com.train.common.utils.StringUtils;
import com.train.mgr.modules.biz.dto.TraineeCourseDetailVo;
import com.train.mgr.modules.biz.dto.TraineeCourseHomeVo;
import com.train.mgr.modules.biz.dto.TraineeCourseUserGroupVo;
import com.train.mgr.modules.biz.dto.TraineeLessonFinishSituationVo;
import com.train.mgr.modules.biz.dto.request.*;
import com.train.mgr.modules.biz.dto.response.CourseCheckUserRespListDTO;
import com.train.mgr.modules.biz.dto.response.CourseUserRespListDTO;
import com.train.mgr.modules.biz.dto.response.NotJoinGroupUserRespListDTO;
import com.train.mgr.modules.biz.entity.*;
import com.train.mgr.modules.biz.mapper.CourseMapper;
import com.train.mgr.modules.biz.mapper.CourseUserMapper;
import com.train.mgr.modules.biz.service.*;
import com.train.mgr.modules.system.entity.User;
import com.train.mgr.modules.system.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 课程学员表 服务实现类
 * </p>
 *
 * @author cxg
 * @date 2025-09-30
 */
@Slf4j
@RequiredArgsConstructor
@Service("ICourseUserService")
public class CourseUserServiceImpl extends ServiceImpl<CourseUserMapper, CourseUser> implements ICourseUserService {

    @Autowired
    private ILessonUserStudyService lessonUserStudyService;

    @Autowired
    private ILessonUserExerciseService lessonUserExerciseService;

    @Autowired
    private ICourseStuGroupService courseStuGroupService;

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private UserService userService;
    @Autowired
    private ILessonService lessonService;
    @Autowired
    private ICourseStuGroupRelService courseStuGroupRelService;

    @Override
    public PageResult<TraineeCourseDetailVo> getMyCourse(TraineeCoursePageDTO req) {
        Page<TraineeCourseDetailVo> page = req.buildPage();
        SysUser currentUser = AuthUtils.getCurrentUser();
        if (currentUser == null){
            throw new BusinessException("请登录");
        }
        Integer state = req.getState();
        Page<TraineeCourseDetailVo> myCourse = baseMapper.getMyCourse(page,req, currentUser.getId(),currentUser.getCustomerId());
        if (myCourse != null){
            for (TraineeCourseDetailVo traineeCourseDetailVo : myCourse.getRecords()) {
                String deadline = traineeCourseDetailVo.getDeadline();
                if (StrUtil.isNotBlank(deadline) && DateUtil.date().after(DateUtil.parse(deadline))){
                    traineeCourseDetailVo.setDeadlineState(1);
                } else {
                    traineeCourseDetailVo.setDeadlineState(0);
                }
                if (StrUtil.isNotBlank(deadline)){
                    traineeCourseDetailVo.setDeadline(DateUtil.format(DateUtil.parse(deadline),"yyyy-MM-dd HH:mm"));
                }
            }
        }
        return PageResult.of(myCourse, TraineeCourseDetailVo.class);
    }

    @Override
    public Integer checkJoinCourseState(Long courseId) {
        return baseMapper.checkJoinCourseState(courseId,AuthUtils.getCurrentUser().getId(),AuthUtils.getCurrentUser().getCustomerId());
    }

    @Override
    public List<TraineeCourseHomeVo> getUserCourse(Long courseId) {
        return baseMapper.getUserCourse(courseId,AuthUtils.getCurrentUser().getCustomerId());
    }

    @Override
    public List<TraineeCourseHomeVo> getUserJoinCourse(Long courseId) {
        return baseMapper.getUserJoinCourse(AuthUtils.getCurrentUser().getId(),
                courseId,AuthUtils.getCurrentUser().getCustomerId());
    }

    @Override
    public List<TraineeCourseHomeVo> getTraineeCourseUser(Long courseId) {
        return baseMapper.getTraineeCourseUser(AuthUtils.getCurrentUser().getId(),courseId,AuthUtils.getCurrentUser().getCustomerId());
    }

    @Override
    public List<TraineeLessonFinishSituationVo> getLessonFinishSituation(Long courseId) {
        return baseMapper.getLessonFinishSituation(AuthUtils.getCurrentUser().getId(),
                courseId,AuthUtils.getCurrentUser().getCustomerId());
    }

    @Override
    public int delByCoursId(Long coursId){
        return baseMapper.delByCoursId(coursId);
    }

    /**
     * 删除课程学员表数据（同时删除学员学习数据）
     * @param id
     * @return
     */
    @Override
    @Transactional
    public int deleteById(Long id){
        CourseUser bean = baseMapper.selectById(id);
        if(ObjectUtil.isEmpty(bean)){
            throw new BizException("记录不存在，无法删除");
        }
        int result = baseMapper.deleteById(bean);
        if(result  >0){
            Long courseId = bean.getCourseId();
            Long userId = bean.getUserId();
            Long customerId = AuthUtils.getCurrentUser().getCustomerId();
            LambdaQueryWrapper<LessonUserExercise> queryUserExeWrapper = new LambdaQueryWrapper<LessonUserExercise>();
            queryUserExeWrapper.eq(LessonUserExercise::getCoruseId,courseId);
            queryUserExeWrapper.eq(LessonUserExercise::getUserId,userId);
            queryUserExeWrapper.eq(LessonUserExercise::getCustomerId,customerId);
            lessonUserExerciseService.remove(queryUserExeWrapper);

            LambdaQueryWrapper<LessonUserStudy> queryUserStudyWrapper = new LambdaQueryWrapper<LessonUserStudy>();
            queryUserStudyWrapper.eq(LessonUserStudy::getCourseId,courseId);
            queryUserStudyWrapper.eq(LessonUserStudy::getUserId,userId);
            queryUserStudyWrapper.eq(LessonUserStudy::getCustomerId,customerId);
            lessonUserStudyService.remove(queryUserStudyWrapper);

            // 删除分组关系表
            LambdaQueryWrapper<CourseStuGroupRel> removeWrapper = Wrappers.lambdaQuery();
            removeWrapper.eq(CourseStuGroupRel::getCourseId,courseId);
            removeWrapper.eq(CourseStuGroupRel::getUserId,userId);
            courseStuGroupRelService.remove(removeWrapper);
        }
        return result;
    }

    @Override
    public PageResult<CourseUserRespListDTO> findCourseUserList(CourseUserQueryDTO params){
        Long customerId = AuthUtils.getCurrentUser().getCustomerId();
        Page<CourseUserRespListDTO> resultPage = baseMapper.selectCourseUserList(params.buildPage(), params.getCourseId(),params.getGroupId(),params.getQ());
        resultPage.getRecords().forEach(x ->{
            Long userId = x.getUserId();
            Long courseId = params.getCourseId();
           // log.info("userId:{},courseId:{}",userId,courseId);
            LambdaQueryWrapper<Lesson> wrapper = Wrappers.<Lesson>lambdaQuery()
                    .eq(Lesson::getCourseId, courseId)
                    .eq(Lesson::getIsPublish, 1)
                    .eq(Lesson::getCustomerId, customerId)
                    .eq(Lesson::getIsDeleted, 0);
            List<Lesson> list = lessonService.list(wrapper);
            List<Long> lessonIds = list.stream().map(Lesson::getId).collect(Collectors.toList());
            //学员学习情况
            List<LessonUserStudy> userStudyList = lessonUserStudyService.findListByCourseId(customerId,lessonIds,courseId,userId);
           // log.info("userStudyList:{}", JSONObject.toJSONString(userStudyList));

            long finishedNum= userStudyList.stream()
                    .filter(cu -> cu.getIsFinish() != null && cu.getIsFinish() == 1)
                    .count();
            x.setUnfinishLessonNum(list.size() - finishedNum);//未完成课时数量
            x.setTotalLessonNum(list.size());//总课时数量


            //学员练习情况
            List<LessonUserExercise> userExerciseList = lessonUserExerciseService.findLessonUserExerciseList(customerId,courseId,userId);
            //log.info("userExerciseList:{}", JSONObject.toJSONString(userExerciseList));
            if(ObjectUtil.isNotEmpty(userExerciseList)){
                //本课程累计完成的练习次数
                Long hasFinishedExerciseCount= userExerciseList.stream()
                        .filter(cu -> cu.getExerciseState() != null && cu.getExerciseState() == 1)
                        .count();
                //本课程累计完成且及格的练习次数
                Long finishedAndPassCount = userExerciseList.stream()
                        .filter(cu -> cu.getExerciseState() != null && cu.getExerciseState() == 1)
                        .filter(cu -> cu.getComprehensiveScore() != null && cu.getPassingScore() != null
                                && cu.getComprehensiveScore().compareTo(cu.getPassingScore()) >= 0)
                        .count();
                //所有的用户练习数
                Integer allExerciseUserCount = userExerciseList.size();
               // log.info("hasFinishedExerciseCount:{},finishedAndPassCount:{},allExerciseUserCount:{}", hasFinishedExerciseCount,finishedAndPassCount,allExerciseUserCount);
                x.setPracticeCount(hasFinishedExerciseCount);//本课程累计完成的练习次数
                x.setPassRate(this.passRate(finishedAndPassCount,allExerciseUserCount));
            }

            //分组名称
            String groupName = courseStuGroupService.findGroupNameByUserId(courseId,userId);
            x.setGroupName(groupName);

        });
        return PageResult.of(resultPage, CourseUserRespListDTO.class);
    }

    @Override
    public PageResult<CourseCheckUserRespListDTO> findCheckCourseUserList(CourseCheckUserQueryDTO params){
        Long customerId = AuthUtils.getCurrentUser().getCustomerId();
        Page<CourseCheckUserRespListDTO> resultPage =  baseMapper.selectCheckCourseUserList(params.buildPage(), params.getCourseId(),customerId);
        return PageResult.of(resultPage, CourseCheckUserRespListDTO.class);
    }

    /**
     * 获取未分组的课程用户信息
     * @param params
     * @return
     */
    @Override
    public PageResult<NotJoinGroupUserRespListDTO> findNoGroupUserList(NoGroupQueryReqDTO params){
        params.setCustomerId(AuthUtils.getCurrentUser().getCustomerId());
        if(!(params.getType()!=null && params.getType() >0)){
            throw new BizException("列表数据类型type参数必须");
        }
        if(!(params.getCourseId()!=null && params.getCourseId() >0)){
            throw new BizException("课程ID必须");
        }
        if(1 != params.getType() && 2 !=params.getType()){
            throw new BizException("列表数据类型type参数值不正确");
        }
      //  log.info("-------------------- "+JSONObject.toJSONString(params));
        Page<NotJoinGroupUserRespListDTO> resultPage =  baseMapper.selectNotGroupUserList(params.buildPage(), params);
        return PageResult.of(resultPage, NotJoinGroupUserRespListDTO.class);
    }

    /**
     * 设置课程学员分组
     * @param dto
     * @return
     */
    @Override
    public boolean setUsersGroup(SetUserGroupReqDTO dto){
        Long courseId = dto.getCourseId();
        Long groupId = dto.getGroupId();
        List<Long> userIds = dto.getUserIds();
        if(ObjectUtil.isEmpty(userIds)){
            throw new BizException("选择用户必须");
        }
        if(!(courseId!=null && courseId >0)){
            throw new BizException("课程ID必须");
        }
        if(!(groupId!=null && groupId >0)){
            throw new BizException("分组ID必须");
        }

        // 3. 根据操作类型统一分支
        switch (dto.getType()) {
            case 1:
                log.info("批量添加学员到分组, courseId={}, groupId={}, userIds={}", courseId, groupId,userIds);
                doGroupUserAdd(courseId, groupId, userIds);
                break;
            case 2:
                log.info("批量移除学员出分组, courseId={}, groupId={}, userIds={}", courseId, groupId, userIds);
                doGroupUserRemove(courseId, groupId, userIds);
                break;
            default:
                throw new BizException("非法操作类型");
        }
        return true;
    }

    /**
     * 批量添加：一次性判断+批量插入
     * @param courseId
     * @param groupId
     * @param userIds
     */
    private void doGroupUserAdd(Long courseId, Long groupId, List<Long> userIds) {
        // 一次性查询已存在的记录
        LambdaQueryWrapper<CourseStuGroupRel> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(CourseStuGroupRel::getCourseId,courseId);
        queryWrapper.eq(CourseStuGroupRel::getGroupId,groupId);
        queryWrapper.in(CourseStuGroupRel::getUserId,userIds);

        List<CourseStuGroupRel> existList =courseStuGroupRelService.list(queryWrapper);
        // 求交集，如果有重复立即失败
        Set<Long> existUserIds = existList.stream()
                .map(CourseStuGroupRel::getUserId)
                .collect(Collectors.toSet());
        if (CollUtil.isNotEmpty(existUserIds)) {
            throw new BizException("学员已存在于分组中，禁止重复添加：" + existUserIds);
        }

        // 3.3 组装实体并批量插入
        List<CourseStuGroupRel> batchList = userIds.stream()
                .map(userId -> new CourseStuGroupRel()
                        .setCourseId(courseId)
                        .setGroupId(groupId)
                        .setUserId(userId))
                .collect(Collectors.toList());
        courseStuGroupRelService.saveBatch(batchList);//批量插入，一次 SQL
    }

    /**
     * 批量移除：一次性判断+批量删除
     */
    private void doGroupUserRemove(Long courseId, Long groupId, List<Long> userIds) {
        // 查询实际存在的记录
        LambdaQueryWrapper<CourseStuGroupRel> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(CourseStuGroupRel::getCourseId,courseId);
        queryWrapper.eq(CourseStuGroupRel::getGroupId,groupId);
        queryWrapper.in(CourseStuGroupRel::getUserId,userIds);
        List<CourseStuGroupRel> existList =courseStuGroupRelService.list(queryWrapper);

        Set<Long> existUserIds = existList.stream()
                                .map(CourseStuGroupRel::getUserId)
                                .collect(Collectors.toSet());
        //求差集，如果有“想删却不存在”的数据立即失败
        Set<Long> notExist = new HashSet<>(userIds);
        notExist.removeAll(existUserIds);
        if (!notExist.isEmpty()) {
            throw new BizException("以下学员不在分组中，无法移除：" + notExist);
        }

        // 4.3 批量删除（按主键）
        List<Long> ids = existList.stream()
                .map(CourseStuGroupRel::getId)
                .collect(Collectors.toList());
        courseStuGroupRelService.removeByIds(ids);   // MyBatis-Plus 批量删除，一次 SQL
    }

    /**
     * 计算合格率（保留 2 位小数，四舍五入）
     * @param finishedAndPassCount 合格且完成人数
     * @param allExerciseUserCount  总人数
     * @return 百分率字符串，如 "85.25%"
     */
    private String passRate(Long finishedAndPassCount, Integer allExerciseUserCount) {
        if (allExerciseUserCount == null || allExerciseUserCount == 0) {
            return "0.00";
        }
        // 转 BigDecimal 避免精度误差
        BigDecimal pass  = BigDecimal.valueOf(finishedAndPassCount == null ? 0L : finishedAndPassCount);
        BigDecimal total = BigDecimal.valueOf(allExerciseUserCount);
        // 保留 2 位小数，四舍五入
        String rate = pass.divide(total, 4, RoundingMode.HALF_UP)
                .multiply(BigDecimal.valueOf(100))
                .setScale(3, RoundingMode.HALF_UP)
                .toPlainString();
        return rate;
    }

    /**
     * tianj
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public boolean add(CourseUserAddDTO dto){
        this.checkParams(dto);
        Long customerId = AuthUtils.getCurrentUser().getCustomerId();
        Course courseObj = courseMapper.selectById(dto.getCourseId());
        if(ObjectUtil.isEmpty(courseObj)){
            throw new BizException("课程信息不存在～");
        }
        List<Long> userIdList = dto.getUserIdList();
        for (Long userId : userIdList) {
            User user = userService.getById(userId);
            if(ObjectUtil.isEmpty(user)){
                log.error("userId:{} 不存在～",userId);
                throw new BizException("用户ID:"+userId+" 不存在～");
            }

            LambdaQueryWrapper<CourseUser> queryCourseUserWrapper = Wrappers.lambdaQuery();
            queryCourseUserWrapper.eq(CourseUser::getCourseId,dto.getCourseId());
            queryCourseUserWrapper.eq(CourseUser::getCustomerId,customerId);
            queryCourseUserWrapper.eq(CourseUser::getUserId,userId);
            long userRows = baseMapper.selectCount(queryCourseUserWrapper);
            if(userRows >0){
                throw new BizException("用户【"+user.getNickName()+"】已存在课程【"+courseObj.getCourseName()+"】，不可重复添加");
            }
            CourseUser bean = new CourseUser();
            //课程是否需要审核
            if("1".equals(courseObj.getReviewState())){
                bean.setReviewStatus(CheckStatusEnum.WAIT_CHECK.getCode()); //审核状态（0：未审核，1：已通过）
            }else{
                bean.setReviewStatus(CheckStatusEnum.APPROVED.getCode()); //审核状态（0：未审核，1：已通过）
                bean.setJoinTime(new Date());
            }
            bean.setCourseId(dto.getCourseId());
            bean.setIsFinish(0);//是否完成课程（0：未完成；1：已完成)
            bean.setNickName(user.getNickName());
            bean.setUserId(user.getId());
            bean.setUserName(user.getUsername());
            bean.setCustomerId(customerId);
            bean.setCreateBy(AuthUtils.getNickname());
            baseMapper.insert(bean);

            if(dto.getGroupId() != null && dto.getGroupId() >0){
                LambdaQueryWrapper<CourseStuGroupRel> queryWrapper = Wrappers.lambdaQuery();
                queryWrapper.eq(CourseStuGroupRel::getCourseId,dto.getCourseId());
                queryWrapper.eq(CourseStuGroupRel::getGroupId,dto.getGroupId());
                queryWrapper.eq(CourseStuGroupRel::getUserId,userId);
                long rows = courseStuGroupRelService.count(queryWrapper);
                if(rows == 0){
                    CourseStuGroupRel stuGroupRel = new CourseStuGroupRel();
                    stuGroupRel.setCourseId(dto.getCourseId());
                    stuGroupRel.setGroupId(dto.getGroupId());
                    stuGroupRel.setUserId(userId);
                    courseStuGroupRelService.save(stuGroupRel);
                }
            }
        }
        return true;
    }

    /**
     * 批量审核
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public boolean batchReview(BatchIdsDTO dto){
        if(ObjectUtil.isEmpty(dto.getIds())){
            throw new BizException("请选择待审核学员");
        }
        if(dto.getStatus() !=null && CheckStatusEnum.APPROVED.getCode() != dto.getStatus()
                && CheckStatusEnum.WAIT_CHECK.getCode()!= dto.getStatus()){
            throw new BizException("参数status值不正确～");
        }

        for (Long id : dto.getIds()) {
            CourseUser entity = baseMapper.selectById(id);
            if(ObjectUtil.isEmpty(entity)){
                throw new BizException("记录为空～");
            }
            if(CheckStatusEnum.APPROVED.getCode()== dto.getStatus()){ //如果是审核通过
                entity.setJoinTime(new Date());
                entity.setReviewStatus(CheckStatusEnum.APPROVED.getCode());//审核状态（0：未审核，1：已通过）
                entity.setUpdateTime(new Date());
                baseMapper.updateById(entity);
            }else{
                int rows = baseMapper.deleteById(entity);
                if(rows > 0){
                    LambdaQueryWrapper<CourseStuGroupRel> removeWrapper = Wrappers.lambdaQuery();
                    removeWrapper.eq(CourseStuGroupRel::getCourseId,entity.getCourseId());
                    removeWrapper.eq(CourseStuGroupRel::getUserId,entity.getUserId());
                    courseStuGroupRelService.remove(removeWrapper);
                }
            }
        }
        return true;
    }

    /**
     * 导入的excel数据验证
     * @param importList
     * @return
     */
    @Override
    public List<StudentImportDTO> checkExcelData(Long courseId,List<StudentImportDTO> importList){
        return this.checkImportData(courseId,importList);
    }

    @Override
    @Transactional
    public boolean saveExcelData(Long courseId,List<StudentImportDTO> importList){
        Course courseObj = courseMapper.selectById(courseId);
        if(ObjectUtil.isEmpty(courseObj)){
            throw new BizException("课程信息不存在～");
        }
//        Integer reviewStatus = 0;//审核状态（0：未审核，1：已通过）
//        //课程是否需要审核（0：否，1：是）
//        if("1".equals(courseObj.getReviewState())){
//            reviewStatus = 1;
//        }
        Long customerId = AuthUtils.getCurrentUser().getCustomerId();
        List<StudentImportDTO> list = this.checkImportData(courseId,importList);
        int importCount = importList.size();
        long passedCount = list.stream().filter(dto -> "检验通过".equals(dto.getMessage())).count();
        log.info("importCount:{},passedCount:{}",importCount,passedCount);
        if(importCount != passedCount) {
            throw new BizException("导入文档有不正确数据，请先进行验证查看异常信息～");
        }
        log.info("importCount == passedCount");
        for(StudentImportDTO paramBean : list){
            Long userId = paramBean.getUserId();//
            CourseUser bean = new CourseUser();
            bean.setReviewStatus(1); //审核状态（0：未通过，1：已通过）
            bean.setJoinTime(new Date());
            bean.setCourseId(courseId);
            bean.setIsFinish(0);//是否完成课程（0：未完成；1：已完成)
            bean.setNickName(paramBean.getNickName());
            bean.setUserId(paramBean.getUserId());
            bean.setUserName(paramBean.getUsername());
            bean.setCustomerId(customerId);
            bean.setCreateBy(AuthUtils.getNickname());
            baseMapper.insert(bean);
            Long courseUserId = bean.getId();
            log.info("courseUserId:{}",courseUserId);

            log.info("paramBean.getGroupName():{},paramBean.getGroupId():{}",paramBean.getGroupName(),paramBean.getGroupId());
            if(StringUtils.isNotBlank(paramBean.getGroupName())){
                    LambdaQueryWrapper<CourseStuGroup> queryWrapper = Wrappers.lambdaQuery();
                    queryWrapper.eq(CourseStuGroup::getGroupName,paramBean.getGroupName());
                    queryWrapper.eq(CourseStuGroup::getCourseId,courseId);
                    queryWrapper.eq(CourseStuGroup::getCustomerId,customerId);
                    CourseStuGroup courseStuGroupBean = courseStuGroupService.getOne(queryWrapper);
                    if(ObjectUtil.isEmpty(courseStuGroupBean)){
                        String nickname = AuthUtils.getNickname();
                        CourseStuGroup courseStuGroup = new CourseStuGroup();
                        courseStuGroup.setCourseId(courseId);
                        courseStuGroup.setGroupName(paramBean.getGroupName());
                        courseStuGroup.setCustomerId(customerId);
                        courseStuGroup.setCreateBy(nickname);
                        courseStuGroup.setCreateTime(new Date());
                        courseStuGroupService.save(courseStuGroup);

                        CourseStuGroupRel stuGroupRel = new CourseStuGroupRel();
                        stuGroupRel.setCourseId(courseId);
                        stuGroupRel.setGroupId(courseStuGroup.getId());
                        stuGroupRel.setUserId(userId);
                        courseStuGroupRelService.save(stuGroupRel);
                    } else{
                        LambdaQueryWrapper<CourseStuGroupRel> queryRelWrapper = Wrappers.lambdaQuery();
                        queryRelWrapper.eq(CourseStuGroupRel::getCourseId,courseId);
                        queryRelWrapper.eq(CourseStuGroupRel::getGroupId,courseStuGroupBean.getId());
                        queryRelWrapper.eq(CourseStuGroupRel::getUserId,userId);
                        long rows = courseStuGroupRelService.count(queryRelWrapper);
                        if(rows == 0){
                            CourseStuGroupRel stuGroupRel = new CourseStuGroupRel();
                            stuGroupRel.setCourseId(courseId);
                            stuGroupRel.setGroupId(courseStuGroupBean.getId());
                            stuGroupRel.setUserId(userId);
                            courseStuGroupRelService.save(stuGroupRel);
                        }
                }
            }

        }
        return true;
    }

    /**
     * 获取用户标签列表
     * @return
     */
    @Override
    public List<String> getUserLabelList(){
        Long customerId = AuthUtils.getCurrentUser().getCustomerId();
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(User::getCustomerId,customerId);
        List<User> userList = userService.list(queryWrapper);
        if(ObjectUtil.isNotEmpty(userList)){
            return userList.stream()               // 创建流
                    .map(User::getUserLable) // 取出每个对象的 userLable
                    .filter(Objects::nonNull) // 可选：去掉 null 值
                    .filter(StrUtil::isNotEmpty)
                    .distinct()          // 去重
                    .collect(Collectors.toList()); // 收集成 List<String>
        }
        return null;
    }

    @Override
    public List<TraineeCourseUserGroupVo> getUserGroupList(Long courseId) {
        return baseMapper.getUserGroupList(courseId);
    }

    private List<StudentImportDTO> checkImportData(Long courseId,List<StudentImportDTO> importList){
        if(CollectionUtil.isEmpty(importList)){
            throw new BusinessException("没有要导入的学员人员数据");
        }
        Map<String, Integer> firstRowMap = new HashMap<>(importList.size());//文档内重复校验辅助

        Long customerId = AuthUtils.getCurrentUser().getCustomerId();
        String userType = UserTypeEnum.EMPLOYEE.getCode().toString();
        List<StudentImportDTO> dataList = new ArrayList<StudentImportDTO>();
        for(int i=0;i<importList.size();i++){
            StudentImportDTO importBean = importList.get(i);
            String username = importBean.getUsername();
            StringBuffer sb = new StringBuffer();
            //String line = "第【"+(i+1)+"】行";
            if(StringUtils.isEmpty(importBean.getNickName())){
                sb.append("【姓名不能为空】;");
            }
            if(StringUtils.isEmpty(username)){
                sb.append("【账号不能为空】;");
            }

            if(StringUtils.isNotBlank(username)){
                Integer firstRow = firstRowMap.put(username, i + 1); // 返回旧值（首次行号）
                if(firstRow != null){
                    sb.append("【该账号在文档中有重复数据】;");
                }
                User user = userService.getByNameAndType(null,username,userType);
                if(ObjectUtil.isEmpty(user)){
                    sb.append("【账号不存在】;");
                }else{
                    Long userCustomerId = user.getCustomerId();
                    if(!customerId.equals(userCustomerId)){
                        sb.append("【账号不存在】;");
                    } else {
                        Long userId = user.getId();
                        //判断是否存在过
                        LambdaQueryWrapper<CourseUser> queryUserWrapper = Wrappers.lambdaQuery();
                        queryUserWrapper.eq(CourseUser::getUserId,userId);
                        queryUserWrapper.eq(CourseUser::getCourseId,courseId);
                        queryUserWrapper.eq(CourseUser::getCustomerId,customerId);
                        long userExists = baseMapper.selectCount(queryUserWrapper);
                        if(userExists >0){
                            sb.append("【账号已是课程学员】;");
                        }else{
                            importBean.setUserId(userId);//后面用到
                        }
                    }
                }
                if(ObjectUtil.isNotEmpty(user) && StringUtils.isNotEmpty(importBean.getNickName())
                        && !importBean.getNickName().equals(user.getNickName())){
                    sb.append("【姓名或账号有误】;");
                }
            }

//            if(StringUtils.isNotBlank(importBean.getGroupName())){
//                LambdaQueryWrapper<CourseStuGroup> queryWrapper = Wrappers.lambdaQuery();
//                queryWrapper.eq(CourseStuGroup::getGroupName,importBean.getGroupName());
//                queryWrapper.eq(CourseStuGroup::getCourseId,courseId);
//                queryWrapper.eq(CourseStuGroup::getCustomerId,customerId);
//                CourseStuGroup courseStuGroupBean = courseStuGroupService.getOne(queryWrapper);
//                if(ObjectUtil.isEmpty(courseStuGroupBean)){
//                    sb.append("【人员分组不存在】;");
//                }else{
//                    importBean.setGroupId(courseStuGroupBean.getId());
//                }
//            }

            importBean.setOrderNo(i+1);
            if(StringUtils.isNotEmpty(sb)){
                importBean.setMessage(sb.toString());
            }else{
                importBean.setMessage("检验通过");
            }

            dataList.add(importBean);
        }
        return dataList;
    }


    private void checkParams(CourseUserAddDTO dto){
        if(ObjectUtil.isEmpty(dto.getUserIdList())){
            throw new BizException("请选择学员");
        }
//        if(dto.getGroupId() == null || dto.getGroupId() ==0){
//            throw new BizException("请选择分组");
//        }
        if(dto.getCourseId() == null || dto.getCourseId() ==0){
            throw new BizException("请选择课程");
        }
    }
}
